package com.wpml.netty.study;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

import java.nio.charset.StandardCharsets;

public class Netty_TimeServer {
    static int counter;

    public static void main(String[] args) {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();

        bootstrap.group(boss, worker)
        .channel(NioServerSocketChannel.class)
        .option(ChannelOption.SO_BACKLOG, 1024)
        .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
                ch.pipeline().addLast(new StringDecoder());
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

                        /*ByteBuf buf = (ByteBuf) msg;
                        byte[] bytes = new byte[buf.readableBytes()];

                        buf.readBytes(bytes);
                        String body = new String(bytes, StandardCharsets.UTF_8)
                                .substring(0, bytes.length - System.getProperty("line.separator").length());*/
                        String body = (String) msg;
                        System.out.println("收到数据：" + body + "; " + ++counter);

                        String retMsg = "服务端相应数据：" + body + System.getProperty("line.separator");
                        ByteBuf writeBuf = Unpooled.copiedBuffer(retMsg.getBytes());
                        ctx.writeAndFlush(writeBuf);
                    }
                });
            }
        });
        try {
            ChannelFuture future = bootstrap.bind(9090).sync();

            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
